<template>
  <view class="address-edit">
    <view class="header">
      <text class="title">{{isEdit ? '编辑地址' : '新增地址'}}</text>
    </view>
    
    <view class="form-container">
      <view class="form-item">
        <text class="label">收货人</text>
        <input 
          type="text"
          v-model="formData.name"
          placeholder="请输入收货人姓名"
          class="input"
          placeholder-class="placeholder"
        />
      </view>
      
      <view class="form-item">
        <text class="label">手机号码</text>
        <input 
          type="number"
          v-model="formData.phone"
          placeholder="请输入手机号码"
          maxlength="11"
          class="input"
          placeholder-class="placeholder"
        />
      </view>
      
      <view class="form-item">
        <text class="label">所在城市</text>
        <picker 
          mode="selector" 
          :range="cities" 
          :value="cityIndex"
          @change="handleCityChange"
          class="picker"
        >
          <view class="picker-content">
            <view class="picker-text" :class="{'placeholder': !formData.city}">
              {{formData.city || '请选择城市'}}
            </view>
            <view class="picker-arrow">
              <text class="arrow-icon">›</text>
            </view>
          </view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="label">小区/大厦</text>
        <input 
          type="text"
          v-model="formData.department"
          placeholder="请输入小区/大厦名称"
          class="input"
          placeholder-class="placeholder"
        />
      </view>
      
      <view class="form-item">
        <text class="label">楼号/门牌</text>
        <input 
          type="text"
          v-model="formData.houseNumber"
          placeholder="请输入详细楼号/门牌号"
          class="input"
          placeholder-class="placeholder"
        />
      </view>
      
      <view class="form-item switch-item">
        <text class="label">设为默认地址</text>
        <switch 
          :checked="formData.isDefault"
          @change="(e) => formData.isDefault = e.detail.value"
          color="#ff6b6b"
          class="custom-switch"
        />
      </view>
      
    </view>
    
    <view class="footer">
      <button class="save-btn" @click="handleSave" hover-class="button-hover">保存</button>
    </view>
  </view>
</template>

<script>
import Config from '@/Config.js'

export default {
  data() {
    return {
      isEdit: false,
      userId: '',
      cities: [],
      cityIndex: 0,
      cityData: [],
      formData: {
        id: '',
        name: '',
        phone: '',
        city: '',
        department: '',
        houseNumber: '',
        isDefault: false
      }
    }
  },
  
  onLoad(options) {
    // 获取用户ID
    const userInfo = uni.getStorageSync('userInfo')
    if (userInfo) {
      this.userId = JSON.parse(userInfo)._id
    }
    
    // 获取城市数据
    this.fetchCities()
    
    // 如果是编辑模式，获取地址信息
    if (options.address) {
      this.isEdit = true
      const address = JSON.parse(decodeURIComponent(options.address))
      this.formData = { ...address }
    }
  },
  
  methods: {
    async fetchCities() {
      try {
        const response = await uni.request({
          url: Config.URL + 'cities',
          method: 'GET'
        })
        
        if (response.statusCode === 200) {
          this.cityData = response.data
          this.cities = response.data.map(city => city.name)
          
          // 如果是编辑模式，设置初始城市索引
          if (this.isEdit && this.formData.city) {
            this.setInitialCityIndex()
          }
        }
      } catch (error) {
        uni.showToast({
          title: '获取城市数据失败',
          icon: 'none'
        })
      }
    },
    
    setInitialCityIndex() {
      const cityIndex = this.cities.findIndex(city => city === this.formData.city)
      if (cityIndex !== -1) {
        this.cityIndex = cityIndex
      }
    },
    
    handleCityChange(e) {
      const cityIndex = e.detail.value
      this.cityIndex = cityIndex
      
      // 更新表单数据
      this.formData.city = this.cities[cityIndex]
    },
    
    validateForm() {
      if (!this.formData.name) {
        uni.showToast({
          title: '请输入收货人姓名',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.phone) {
        uni.showToast({
          title: '请输入手机号码',
          icon: 'none'
        })
        return false
      }
      
      if (!/^1[3-9]\d{9}$/.test(this.formData.phone)) {
        uni.showToast({
          title: '手机号码格式不正确',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.city) {
        uni.showToast({
          title: '请选择所在城市',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.department) {
        uni.showToast({
          title: '请输入小区/大厦名称',
          icon: 'none'
        })
        return false
      }
      
      if (!this.formData.houseNumber) {
        uni.showToast({
          title: '请输入楼号/门牌号',
          icon: 'none'
        })
        return false
      }
      
      return true
    },
    
    async handleSave() {
      if (!this.validateForm()) return
      
      try {
        // 先获取用户数据
        const getUserResponse = await uni.request({
          url: Config.URL + 'users',
          method: 'GET'
        })
        
        if (getUserResponse.statusCode !== 200) {
          throw new Error('获取用户数据失败')
        }
        
        const users = getUserResponse.data
        const currentUser = users.find(user => user.id === this.userId)
        
        if (!currentUser) {
          throw new Error('用户不存在')
        }
        
        // 准备地址数据
        let addresses = currentUser.addresses || []
        const now = new Date().toISOString()
        
        // 如果是新建地址且是第一个地址，则设为默认地址
        if (!this.isEdit && addresses.length === 0) {
          this.formData.isDefault = true
        }
        
        // 如果当前地址设置为默认，需要将其他地址的默认状态取消
        if (this.formData.isDefault) {
          addresses = addresses.map(addr => ({
            ...addr,
            isDefault: false
          }))
        }
        
        if (this.isEdit) {
          // 编辑模式：更新现有地址
          addresses = addresses.map(addr => 
            addr.id === this.formData.id 
              ? { ...this.formData, updatedAt: now }
              : addr
          )
        } else {
          // 新建模式：添加新地址
          const newAddress = {
            ...this.formData,
            id: Date.now().toString(),
            createdAt: now,
            updatedAt: now
          }
          addresses.push(newAddress)
        }
        
        // 更新用户数据
        const updateResponse = await uni.request({
          url: Config.URL + `users/${this.userId}`,
          method: 'PUT',
          data: {
            ...currentUser,
            addresses
          }
        })
        
        if (updateResponse.statusCode === 200) {
          // 更新本地存储的用户信息
          const userInfo = uni.getStorageSync('userInfo');
          if (userInfo) {
            const parsedUserInfo = JSON.parse(userInfo);
            parsedUserInfo.addresses = addresses;
            uni.setStorageSync('userInfo', JSON.stringify(parsedUserInfo));
          }
          
          uni.showToast({
            title: this.isEdit ? '修改成功' : '添加成功',
            icon: 'success'
          })
          
          // 返回上一页并刷新地址列表
          setTimeout(() => {
            const pages = getCurrentPages()
            const prevPage = pages[pages.length - 2]
            if (prevPage && prevPage.$vm.fetchAddresses) {
              prevPage.$vm.fetchAddresses()
            }
            uni.navigateBack()
          }, 1500)
        } else {
          throw new Error('保存失败')
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '保存失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss">
.address-edit {
  min-height: 100vh;
  background-color: #f8f9fa;
  
  .header {
    background-color: #fff;
    padding: 30rpx;
    text-align: center;
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    position: sticky;
    top: 0;
    z-index: 100;
    
    .title {
      font-size: 36rpx;
      font-weight: 600;
      color: #2c3e50;
    }
  }
  
  .form-container {
    background-color: #fff;
    margin: 20rpx;
    border-radius: 16rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    overflow: hidden;
    
    .form-item {
      display: flex;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid #f0f0f0;
      transition: all 0.3s ease;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:active {
        background-color: #f8f9fa;
      }
      
      .label {
        width: 160rpx;
        font-size: 28rpx;
        color: #2c3e50;
        font-weight: 500;
      }
      
      .input {
        flex: 1;
        font-size: 28rpx;
        color: #2c3e50;
        padding: 10rpx 0;
      }
      
      .placeholder {
        color: #95a5a6;
      }
      
      .picker {
        flex: 1;
        height: 60rpx;
        line-height: 60rpx;
        position: relative;
        
        &::after {
          content: '';
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 1px;
          height: 30rpx;
          background-color: #eee;
        }
        
        .picker-content {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 100%;
          padding-right: 20rpx;
        }
        
        .picker-text {
          font-size: 28rpx;
          color: #2c3e50;
          height: 100%;
          flex: 1;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          
          &.placeholder {
            color: #95a5a6;
          }
        }
        
        .picker-arrow {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 40rpx;
          height: 40rpx;
          margin-left: 10rpx;
          
          .arrow-icon {
            color: #95a5a6;
            font-size: 36rpx;
            transform: rotate(90deg);
            font-weight: 300;
          }
        }
      }
      
      &.switch-item {
        justify-content: space-between;
        
        .custom-switch {
          transform: scale(0.9);
        }
      }
    }
  }
  
  .footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 30rpx;
    background-color: #fff;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .save-btn {
      background: linear-gradient(135deg, #ff6b6b, #ff8787);
      color: #fff;
      border-radius: 50rpx;
      font-size: 32rpx;
      font-weight: 600;
      padding: 20rpx 0;
      border: none;
      transition: all 0.3s ease;
      
      &.button-hover {
        transform: scale(0.98);
        opacity: 0.9;
      }
    }
  }
}
</style>
